//
// Created by 崔世强 on 2018/3/15.
// Copyright (c) 2018 Facebook. All rights reserved.
//

import Foundation
import WebKit
import UIKit
import SnapKit
import Social

struct Param {
    enum ParamType {
        case url
        case file
    }
    
    init(url: URL) {
        self.type = .url
        self.url = url
    }
    
    init(fileName: String, ext: String, storeFile: String, size: Int) {
        self.type = .file
        self.fileName = fileName
        self.ext = ext
        self.storeFile = storeFile
        self.size = size
    }
    
    
    var type: ParamType
    var fileName: String?
    var ext: String?
    var storeFile: String?
    var size: Int?
    var url: URL?
}

class ChatWebBrowserController: ChatBaseController {
    
    var closeBtnClicked: Bool = false
    
    lazy var webView: WKWebView = {
        let webConfiguration = WKWebViewConfiguration()
        let web = WKWebView(frame: view.bounds, configuration: webConfiguration)
        web.allowsBackForwardNavigationGestures = true
        if #available(iOS 11, *) {  //适配iphone x，不会让下面的home indicator 挡住页面最下面
            web.scrollView.contentInsetAdjustmentBehavior = .automatic
        }
        web.navigationDelegate = self
        web.uiDelegate = self
        if #available(iOS 9, *) {
            web.allowsLinkPreview = false
        }
        web.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
        
        return web
    }()
    
    lazy var progressView: UIProgressView = {
        let progress = UIProgressView()
        progress.progressTintColor = UIColor.green
        progress.trackTintColor = .clear
        return progress
    }()
    
    lazy var backButtonItem: UIBarButtonItem = {
        let button = UIButton(type: .custom)
        button.setTitle("返回", for: .normal)
        button.setImage(#imageLiteral(resourceName:"barbuttonicon_back"), for: .normal)
        button.sizeToFit()
        
        button.contentEdgeInsets = UIEdgeInsets(top: 0, left: -10, bottom: 0, right: 0);
        button.setTitleColor(UIColor.white, for: .normal)
        button.setTitleColor(UIColor.gray, for: .highlighted)
        button.addTarget(self, action: #selector(back), for: .touchUpInside)
        
        let backItem = UIBarButtonItem(customView: button)
        
        
        //        let backItem = UIBarButtonItem(title: "返回", style: .plain, target: self, action: #selector(back))
        //        let backItem = UIBarButtonItem(image:#imageLiteral(resourceName:"barbuttonicon_back"), style: .plain, target: self, action: #selector(back))
        //        backItem.title = "返回"
        //        backItem.setBackgroundImage(#imageLiteral(resourceName:"barbuttonicon_back"), for: .normal, barMetrics: .default)
        return backItem
    }()
    
    lazy var closeButtonItem: UIBarButtonItem = {
        return UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(close))
    }()
    
    lazy var optionButtonItem: UIBarButtonItem = {
        let barItem = UIBarButtonItem(title: "", style: .plain, target: self, action: #selector(option))
        barItem.image = #imageLiteral(resourceName:"barbuttonicon_more")
        return barItem
    }()
    
    
    lazy var fileIcon: UIImageView = {
        let icon = UIImageView(image: #imageLiteral(resourceName:"defaultFile"))
        return icon
    }()
    
    lazy var fileName: UILabel = {
        let file = UILabel()
        file.numberOfLines = 0
        file.textAlignment = .center
        file.font = UIFont.systemFont(ofSize: 18.0)
        file.lineBreakMode = .byTruncatingMiddle
        return file
    }()
    
    lazy var fileSize: UILabel = {
        let file = UILabel()
        file.numberOfLines = 1
        file.textAlignment = .center
        file.font = UIFont.systemFont(ofSize: 12.0)
        file.textColor = .lightGray
        file.lineBreakMode = .byTruncatingMiddle
        return file
    }()
    
    lazy var downloadBtn: UIButton = {
        let downloadBtn = UIButton(frame: CGRect(x: 0, y: 0, width: (UIScreen.main.bounds.width - CGFloat(30)), height: 40))
        //        let deleteButton = UIButton(frame:CGRect.zero)
        downloadBtn.setTitle("开始下载", for: .normal)
        downloadBtn.backgroundColor = UIColor(red: 79 / 255, green: 169 / 255, blue: 56 / 255, alpha: 1)
        downloadBtn.layer.cornerRadius = 5 //设置圆角
        downloadBtn.addTarget(self, action: #selector(startDownload), for: .touchUpInside)
        return downloadBtn
    }()
    
    lazy var downloadProgress: UIProgressView = {
        let progress = UIProgressView()
        progress.progressTintColor = UIColor(red: 79 / 255, green: 169 / 255, blue: 56 / 255, alpha: 1)
        progress.trackTintColor = .gray
        progress.isHidden = true
        return progress
    }()
    
    lazy var pauseBtn: UIButton = {
        let pauseBtn = UIButton(frame: CGRect(x: 0, y: 0, width: (UIScreen.main.bounds.width - CGFloat(30)), height: 30))
        //        let deleteButton = UIButton(frame:CGRect.zero)
        pauseBtn.setTitle("开始下载", for: .normal)
        pauseBtn.backgroundColor = .red
        pauseBtn.layer.cornerRadius = 5 //设置圆角
        pauseBtn.addTarget(self, action: #selector(pauseDownload), for: .touchUpInside)
        return downloadBtn
    }()
    
    lazy var fileInfoView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.isHidden = true
        return view
    }()
    
    
    var url: URL?
    var param: Param!
    
    var fileNameText: String {
        return "\(param.fileName ?? "unknown").\(param.ext ?? "unknown")"
    }
    
    deinit {
        self.webView.removeObserver(self, forKeyPath: "estimatedProgress")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNavigation()
        makeConstraints()
        
        switch param.type {
        case .url:
            if let web = param.url {
                self.webView.load(URLRequest(url: web))
            }
        case .file:
            self.fileName.text = fileNameText
            self.fileSize.text = Common.getSizeString(size: param.size ?? 0)
            self.navigationItem.title = fileNameText
            setFileIcon()
            handleFile()
        default:
            break
        }
        
    }
    
    
    func setFileIcon() {
        if let ext = param.ext {
            if ext == "doc" || ext == "docx" {
                fileIcon.image = #imageLiteral(resourceName:"wordFile")
            } else if ext == "xls" || ext == "xlsx" {
                fileIcon.image = #imageLiteral(resourceName:"excelFile")
            } else if ext == "pdf" {
                fileIcon.image = #imageLiteral(resourceName:"pdfFile")
            } else if ext == "txt" || ext == "text" {
                fileIcon.image = #imageLiteral(resourceName:"txtFile")
            } else if ext == "ppt" || ext == "pptx" {
                fileIcon.image = #imageLiteral(resourceName:"pptFile")
            } else {
                fileIcon.image = #imageLiteral(resourceName:"defaultFile")
            }
        }
    }
    
    var forceUpdate = false  //调试使用，为true时总是显示下载页面
    
    func handleFile() {
        let cacheDir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0] as URL
        let fileUrl = cacheDir.appendingPathComponent("files/\(param.storeFile ?? "unknown.unknown")", isDirectory: false)
        if FileManager.default.fileExists(atPath: fileUrl.path) && !forceUpdate {
            self.optionButtonItem.isEnabled = false
            self.fileInfoView.isHidden = true
            self.webView.isHidden = false
            if #available(iOS 9, *) {
                self.webView.loadFileURL(fileUrl, allowingReadAccessTo: fileUrl)
            } else {
                do {
                    let url = try fileForIOS8(fileUrl)
                    self.webView.load(URLRequest(url: url))
                } catch {
                    print(error)
                }
            }
        } else {
            self.optionButtonItem.isEnabled = false
            self.fileInfoView.isHidden = false
            self.downloadProgress.isHidden = true
            self.downloadBtn.isHidden = false
            self.webView.isHidden = true
        }
    }
    
    func fileForIOS8(_ url: URL) throws -> URL {
        let tmpPath = NSTemporaryDirectory() + url.lastPathComponent
        try FileManager.default.copyItem(atPath: url.path, toPath: tmpPath)
        return URL(fileURLWithPath: tmpPath)
    }
    
    private func makeConstraints() {
        self.view.addSubview(self.webView)
        self.view.addSubview(self.progressView)
        
        fileInfoView.addSubview(fileIcon)
        fileInfoView.addSubview(fileName)
        fileInfoView.addSubview(fileSize)
        fileInfoView.addSubview(downloadProgress)
        fileInfoView.addSubview(downloadBtn)
        self.view.addSubview(fileInfoView)
        
        self.fileInfoView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            if #available(iOS 11, *) {
                make.top.equalTo(self.view.safeAreaLayoutGuide)
            } else {
                self.edgesForExtendedLayout = []
                make.top.equalTo(self.view)
            }
        }
        
        self.fileIcon.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(30)
            make.width.height.equalTo(80)
            make.centerX.equalToSuperview()
        }
        
        self.fileName.snp.makeConstraints { make in
            make.top.equalTo(fileIcon.snp.bottom).offset(10)
            make.left.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(30)
        }
        self.fileSize.snp.makeConstraints { make in
            make.top.equalTo(fileName.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(20)
        }
        self.downloadBtn.snp.makeConstraints { make in
            make.top.equalTo(fileSize.snp.bottom).offset(10)
            make.width.equalToSuperview().offset(-30)
            make.centerX.equalToSuperview()
        }
        
        self.downloadProgress.snp.makeConstraints { make in
            make.top.equalTo(fileSize.snp.bottom)
            make.width.equalToSuperview().offset(-30)
            make.height.equalTo(10)
            make.centerX.equalToSuperview()
        }
        
        self.progressView.snp.makeConstraints { make in
            make.left.right.equalTo(self.view)
            if #available(iOS 11, *) {
                make.top.equalTo(self.view.safeAreaLayoutGuide)
            } else {
                self.edgesForExtendedLayout = []
                make.top.equalTo(self.view)
            }
            make.height.equalTo(2)
        }
        
        self.webView.snp.makeConstraints { make in
            make.left.right.bottom.equalTo(self.view)
            if #available(iOS 11, *) {
                make.top.equalTo(self.view.safeAreaLayoutGuide)
            } else {
                make.top.equalTo(self.view)
            }
        }
    }
    
    
    private var navigationDelegate: UIGestureRecognizerDelegate?
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: true)
        self.progressView.isHidden = false
        UIView.animate(withDuration: 1.0) {
            self.progressView.progress = 0.0
        }
        
        //覆盖导航控件默认侧滑行为
        self.navigationDelegate = self.navigationController?.interactivePopGestureRecognizer?.delegate
        self.navigationController?.interactivePopGestureRecognizer?.delegate = self
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        //还原导航控件侧滑行为
        self.navigationController?.interactivePopGestureRecognizer?.delegate = self.navigationDelegate
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        
    }
    
    private func setupNavigation() {
        self.navigationItem.leftBarButtonItems = [self.backButtonItem]
        //        self.navigationItem.leftBarButtonItems = [self.closeButtonItem]
        self.navigationItem.rightBarButtonItems = [self.optionButtonItem]
        self.view.backgroundColor = UIColor(red: 235 / 255, green: 235 / 255, blue: 235 / 255, alpha: 1)
    }
}

extension ChatWebBrowserController {
    @objc func back() {
        if webView.canGoBack {
            webView.goBack()
        } else {
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    @objc func close() {
        closeBtnClicked = true
        self.navigationController?.popViewController(animated: true)
    }
    
    @objc func option() {
        if let pageUrl = self.webView.url {
            let items = [pageUrl]
            let shareController = UIActivityViewController(activityItems: items, applicationActivities: nil)
            self.navigationController?.present(shareController, animated: true)
        }
        
    }
    
    @objc func startDownload() {
        downloadBtn.isHidden = true
        downloadProgress.isHidden = false
        imResources.request(.file(fileName: param.storeFile ?? "unknown.unknown"), progress: { progress in
            DispatchQueue.main.async {
                UIView.animate(withDuration: 0.1) {
                    self.downloadProgress.progress = Float(progress.progress)
                }
            }
        }) { result in
            switch result {
            case .success:
                let localLocation: URL = DefaultDownloadDir.appendingPathComponent(self.param.storeFile ?? "unknown.unknown")
                print("下载完毕！保存地址：\(localLocation)")
                DispatchQueue.main.async {
                    self.handleFile()
                }
            case let .failure(error):
                print(error)
                DispatchQueue.main.async {
                    /// 弹出提示框点击确定返回
                    let alertView = UIAlertController.init(title: nil, message: "文件已过期或被清理", preferredStyle: .alert)
                    let okAction = UIAlertAction.init(title: "确定", style: .default) { okAction in
                        self.downloadBtn.isHidden = false
                        self.downloadProgress.isHidden = true
                    }
                    alertView.addAction(okAction)
                    self.present(alertView, animated: true, completion: nil)
                }
            }
        }
    }
    
    @objc func pauseDownload() {
        
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
        if "estimatedProgress" == keyPath {
            UIView.animate(withDuration: 0.5) {
                self.progressView.progress = change?[NSKeyValueChangeKey(rawValue: "new")] as? Float ?? 0
            }
        }
    }
}

extension ChatWebBrowserController: UIGestureRecognizerDelegate {
    
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        return (self.navigationController?.viewControllers.count ?? 0) > 1
    }
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return (self.navigationController?.viewControllers.count ?? 0) > 1
    }
}

extension ChatWebBrowserController: WKNavigationDelegate {
    
    // 页面开始加载时调用
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        self.navigationItem.title = "加载中..."
        setProgressView(hide: false)
        UIView.animate(withDuration: 0.5) {
            self.progressView.progress = 0.1
        }
    }
    
    // 当内容开始返回时调用
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        
        
    }
    
    // 页面加载完成之后调用
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        /// 获取网页title
        switch param.type {
        case .url:
            self.navigationItem.title = self.webView.title
        case .file:
            self.optionButtonItem.isEnabled = true
            self.navigationItem.title = fileNameText  //显示文件名
        }
        
        setProgressView(hide: true)
        
        if webView.canGoBack {
            self.navigationItem.leftBarButtonItems = [self.backButtonItem, self.closeButtonItem]
        } else {
            self.navigationItem.leftBarButtonItems = [self.backButtonItem]
        }
    }
    
    // 页面加载失败时调用
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: NSError) {
        UIView.animate(withDuration: 0.5) {
            self.progressView.progress = 0.0
        }
        setProgressView(hide: true)
        
        //忽略用户操作行为导致的请求取消异常
        if error.code == NSURLErrorCancelled {
            return
        }
        
        /// 弹出提示框点击确定返回 // todo 寻找更优雅的方式解决加载失败的情况
        let alertView = UIAlertController.init(title: "提示", message: "加载失败", preferredStyle: .alert)
        let okAction = UIAlertAction.init(title: "确定", style: .default) { okAction in
            //            _=self.navigationController?.popViewController(animated: true)
        }
        alertView.addAction(okAction)
        self.present(alertView, animated: true, completion: nil)
        
    }
    
    func setProgressView(hide: Bool) {
        UIView.animate(withDuration: 0.5) {
            self.progressView.isHidden = hide
        }
    }
}

extension ChatWebBrowserController: WKUIDelegate {
    
}


extension ChatWebBrowserController: UINavigationBarDelegate {
    
    func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {
        if webView.canGoBack {
            webView.goBack()
            return false
        }
        if closeBtnClicked {
            return false
        }
        return true
    }
}

//public protocol ShouldPopDelegate
//{
//    func currentViewControllerShouldPop() -> Bool
//}

//extension UIViewController: ShouldPopDelegate
//{
//    public func currentViewControllerShouldPop() -> Bool {
//        return true
//    }
//}

//
//extension UINavigationController: UINavigationBarDelegate
//{
//    public func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool
//    {
//        var shouldPop = true
//        // 看一下当前控制器有没有实现代理方法 currentViewControllerShouldPop
//        // 如果实现了，根据当前控制器的代理方法的返回值决定
//        // 没过没有实现 shouldPop = YES
//        let currentVC = self.topViewController
////        if (currentVC?.responds(to: #selector(currentViewControllerShouldPop)))! {
//        shouldPop = (currentVC?.currentViewControllerShouldPop())!
////        }
//
//        if (shouldPop == true)
//        {
//            DispatchQueue.main.async {
//                self.popViewController(animated: true)
//            }
//            // 这里要return, 否则这个方法将会被再次调用
//            return true
//        }
//        else
//        {
//            // 让系统backIndicator 按钮透明度恢复为1
//            for subview in navigationBar.subviews
//            {
//                if (0.0 < subview.alpha && subview.alpha < 1.0) {
//                    UIView.animate(withDuration: 0.25, animations: {
//                        subview.alpha = 1.0
//                    })
//                }
//            }
//            return false
//        }
//    }
//}
